package net.m510.autosurfer;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.m510.autosurfer.common.cli.OutDirOption;
import net.m510.autosurfer.common.cli.PasswordOption;
import net.m510.autosurfer.common.exception.InvalidDocumentException;
import net.m510.autosurfer.core.AbstractMain;
import net.m510.autosurfer.core.exception.UserProcessException;
import net.m510.autosurfer.nifty.NiftyBillSave;
import net.m510.autosurfer.nifty.NiftyGoTop;
import net.m510.autosurfer.nifty.NiftyLogin;
import net.m510.autosurfer.nifty.NiftyLoginChecker;
import net.m510.autosurfer.nifty.NiftyLogout;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


public class NiftyGetMain extends AbstractMain {
	private static final Logger log = Logger.getLogger(NiftyGetMain.class.getName());
	public static final String MEISAI_FILENAME="bill.html";
	public static final String MEISAI_FILENAME_FORMAT="bill_%4d%02d.html";
	public static final String DEFAULT_MEISAI_DIRNAME=".";
	
	String userId;
	String password;
	File outDir;
	private String charset;
	
	/**
	 * 
	 */
	public NiftyGetMain() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		NiftyGetMain main = new NiftyGetMain();
		main.setLogger(log);
		main.Main(args);
	}
	
	@Override
	protected Document start() throws ClientProtocolException, IOException, UserProcessException {
		return new NiftyGoTop(client,context).process(null);
	}

	@Override
	protected Document login(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		NiftyLogin p = new NiftyLogin(client, context);
		p.setUserId(userId);
		p.setPassword(password);
		Document out = p.process(doc);
		
		new NiftyLoginChecker().check(out);
		this.charset = p.getActualCharset();
		
		return out;
	}

	@Override
	protected Document prepareDownload(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		return doc;
	}

	@Override
	protected File download(Document doc) throws IOException, UserProcessException {
		// ファイル名を作成
		final String CLASS_KEY="hdg_l2_01";
		Elements elems = doc.getElementsByClass(CLASS_KEY);
		if ( elems.size() == 0 ) throw new InvalidDocumentException("could not find class "+CLASS_KEY, doc);
		final String REGEX="([0-9]{4})年([0-9]{1,2})";
		Matcher m = Pattern.compile(REGEX).matcher(elems.first().text());
		if ( !m.find() ) throw new InvalidDocumentException("did not match regex("+REGEX+")",doc);
		log.fine("matched group="+m.group()+", group count="+m.groupCount());
		String filename = String.format(MEISAI_FILENAME_FORMAT, Integer.parseInt(m.group(1)),Integer.parseInt(m.group(2)));
		log.fine("filename="+filename);
		
		NiftyBillSave p = new NiftyBillSave(client,context,outDir,filename,charset);
		File f = p.process(doc).get(0);
		
		return f;
	}

	@Override
	protected void logout(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		NiftyLogout p =  new NiftyLogout(client, context);
		Document out = p.process(doc);
		p.check(out);
	}
	
	@SuppressWarnings("static-access")
	@Override
	protected Options getOptions() {
		Options options = new Options();
		Option out = new OutDirOption(false);options.addOption(out);
		options.addOption(OptionBuilder.hasArg(true).withArgName("@nifty id")
				.isRequired(true).withDescription("@niftyユーザー名または@nifty id")
				.create("id"));
		Option password = new PasswordOption(true); options.addOption(password);
		return options;
	}

	@Override
	protected void setParams(CommandLine cmd) {
		userId = cmd.getOptionValue("id");
		this.password = cmd.getOptionValue(PasswordOption.OPT);
		outDir = new File(cmd.getOptionValue(OutDirOption.OPT, DEFAULT_MEISAI_DIRNAME));
	}

}
